//==========Ajax请求=============
function ajax(url, method, data, isAsync, success_callback, error_callback, wait) {
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader("token", localStorage.token);
        }
    });
    if (wait) modals.wait("/common/img/loading.gif");
    var header = {
        url: url,
        data: data,
        type: method,
        dataType: 'json',
        async: isAsync,
        traditional:true
    }
    if (data instanceof FormData) $.extend(header, {contentType: false, processData: false, cache: false})

    $.ajax($.extend(header, {
        success: function (result) {
            modals.closeWait();
            if (result.code != 0) {
                if (result.code == 100) {
                    localStorage.removeItem("token")
                    window.location.href = "/login"
                } else {
                    modals.error(result.message);
                    if (error_callback) error_callback(result.message);
                }
            } else {
                if (success_callback) success_callback(result.data);
            }
        },
        error: function () {
            modals.closeWait();
        }
    }))
}

function ajaxDownload(url, type, params, error_callback, wait) {
    if (wait) modals.wait("/common/img/loading.gif");

    var request = new XMLHttpRequest();
    request.onload = function (oEvent) {
        modals.closeWait();
        var arrayBuffer = request.response; // Note: not oReq.responseText
        var responseHeader = {};
        request.getAllResponseHeaders().split("\n")
            .filter(function (string) {
                return string != ""
            }).forEach(function (string) {
                var array = string.split(":");
                var object = {};
                object[array[0]] = array[1];
                $.extend(responseHeader, object);
            });
        if (responseHeader["content-type"].indexOf("application/json") != -1) {
            ab2str(arrayBuffer, function (result) {
                result = JSON.parse(result);
                modals.error(result.message);
                if (error_callback) error_callback(result.message);
            })
        } else {
            var index = responseHeader["content-disposition"].indexOf("filename");
            var filename = responseHeader["content-disposition"].substring(index + "filename".length + 2);
            filename = decodeURI(filename.substring(0, filename.length - 2));
            var blob = new Blob([arrayBuffer], {type: responseHeader["content-type"]});
            var url = URL.createObjectURL(blob);
            downloadFile(url, filename);
        }
    }
    if (type == "get") {
        url += "?";
        for (var i in params) {
            url += i + "=";
            url += params[i] + "&";
        }
        url = url.substring(0, url.length - 1);
    }
    request.open(type, url, true);
    request.responseType = "arraybuffer";
    request.onerror = function(event){modals.closeWait(); }
    request.setRequestHeader("token", localStorage.token);
    request.send(params);
}

function postFileDownload(url, params, error_callback, wait) {
    ajaxDownload(url, "post", params, error_callback, wait)
}

function getFileDownload(url, params, error_callback, wait) {
    ajaxDownload(url, "get", params, error_callback, wait)
}

//异步
function AsyncPost(url, data, success_callback, error_callback, wait) {
    ajax(url, "post", data, true, success_callback, error_callback, wait);
}

function AsyncGet(url, data, success_callback, error_callback, wait) {
    ajax(url, "get", data, true, success_callback, error_callback, wait);
}

function AsyncPut(url, data, success_callback, error_callback, wait) {
    ajax(url, "put", data, true, success_callback, error_callback, wait);
}

function AsyncDelete(url, data, success_callback, error_callback, wait) {
    ajax(url, "delete", data, true, success_callback, error_callback, wait);
}

//同步
function SyncPost(url, data, success_callback, error_callback, wait) {
    ajax(url, "post", data, false, success_callback, error_callback, wait);
}

function SyncGet(url, data, success_callback, error_callback, wait) {
    ajax(url, "get", data, false, success_callback, error_callback, wait);
}

function AsyncPut(url, data, success_callback, error_callback, wait) {
    ajax(url, "put", data, false, success_callback, error_callback, wait);
}

function SyncDelete(url, data, success_callback, error_callback, wait) {
    ajax(url, "delete", data, false, success_callback, error_callback, wait);
}
